import React, { Component } from 'react';
import { Input, Button, Divider, Card, Table } from 'antd';
import { clone, map, findIndex, isEmpty, isFunction, omit } from 'lodash';
import PositionDetail from './Detail';
import { isObjectValEqual } from '/common/utils/utils';

import Animate from 'rc-animate';
import 'rc-table/assets/index.css';
import 'rc-table/assets/animation.css';

const AnimateBody = props => <Animate transitionName="move" component="tbody" {...props} />;

const { Group } = Input;

export default class Position extends Component {

  constructor(props) {
    super(props);
    this.state = {
      list: map(props.list, (v) => ({...v, key: v.id})) || [],
      selectedRowKeys: [],
      isShowDetail: false,
      detail: {},
      acting: false
    };
  }

  componentDidMount() {
    isFunction(this.props.onRef) && (this.props.onRef(this.props.refKey, this));
  }

  componentDidUpdate(prevProps, prevState) {
    if (!isObjectValEqual(prevProps, this.props)) {
      this.setState({ list: map(this.props.list, (v) => ({...v, key: v.id})) });
    }
  }

  getAjaxData() {
    return new Promise((resolve, reject) => {
      resolve(map(this.state.list, (v) => (omit(v, ['key']))));
    });
  }

  setStateActing(state) {
    if(!this.state.acting) {
      this.setState({acting: true}, () => {
        this.setState(state);
      });
    } else {
      this.setState(state);
    }
  }

  showDetail(eOrRecord) {
    let record = {};
    if (!isEmpty(eOrRecord) && eOrRecord.code) {
      record = eOrRecord;
    }

    this.setState({
      detail: record,
      isShowDetail: true,
    });
  }

  handleDel(ind) {
    if (!isNaN(parseInt(ind))) {
      const { list } = this.state;
      const newList = clone(list);
      newList.splice(parseInt(ind), 1);
      this.setStateActing({
        list: newList
      });
    }
  }

  handleMultiDel() {
    const { selectedRowKeys, list } = this.state;
    console.log(selectedRowKeys);
    if (selectedRowKeys.length > 0) {
      const newList = clone(list);
      selectedRowKeys.forEach((v) => {
        let ind = findIndex(newList, o => (o.key === v));
        if (-1 !== ind) {
          newList.splice(ind, 1);
        }
      });
      this.setStateActing({
        list: newList,
        selectedRowKeys: []
      });
    }
  }

  onSaveDetail(data) {
    // console.log(data);
    const { list } = this.state;
    if ('undefined' !== typeof data.key && !isNaN(parseInt(data.key))) { // 编辑
      const ind = findIndex(list, (v) => (v.key === data.key));
      if (-1 !== ind) {
        const newList = clone(list);
        newList.splice(ind, 1, data);
        this.setStateActing({
          list: newList,
          isShowDetail: false
        });
        return;
      }
    }

    // 添加
    this.setStateActing({
      list: clone(list).concat([{ key: Math.floor((+new Date()) / 1000), ...data }]),
      isShowDetail: false
    });
  }

  onSelectChange(selectedRowKeys) {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  }

  render() {
    const { selectedRowKeys, list } = this.state;
    const action = (
      <Group>
        <Button type="primary" size='small' style={{ marginRight: 8 }}
                onClick={this.showDetail.bind(this)}>新增岗位</Button>
        <Button type="danger" disabled={selectedRowKeys.length <= 0} size='small'
                onClick={this.handleMultiDel.bind(this)}>批量删除</Button>
      </Group>
    );

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
    };

    const tableProps = {
      rowSelection,
      scroll: { y: document.body.offsetHeight-480, x: false },
      dataSource: list,
      columns: [
        {
          title: '序号',
          dataIndex: 'no',
          key: 'no',
          render: (text, record, index) => (index + 1),
        },
        {
          title: '岗位编码',
          dataIndex: 'code',
          key: 'code',
        },
        {
          title: '岗位名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '操作',
          key: 'action',
          render: (text, record, index) => (
            <>
              <a href="javascript:;" onClick={this.showDetail.bind(this, record)}>编辑</a>
              <Divider type="vertical"/>
              <a href="javascript:;" onClick={this.handleDel.bind(this, index)}>删除</a>
            </>
          ),
        },
      ],
    };

    if(this.state.acting) {
      tableProps.components = {
        body: { wrapper: AnimateBody },
      };
    }

    return (
      <>
        <Card size='small'
              type="inner"
              title={'岗位列表'}
              extra={action}
              bodyStyle={{ padding: '16px 16px 0' }}
        >
          <Table size='small'  {...tableProps}
          />
        </Card>
        <PositionDetail
          isShowDetail={this.state.isShowDetail}
          saveDetail={this.onSaveDetail.bind(this)}
          onCancel={() => {
            this.setState({ isShowDetail: false });
          }}
          detail={this.state.detail}
        />
      </>
    );
  }
}
